<?php
/**
 * sdPHP
 * @author     码农<8044023@qq.com>
 * @copyright  sdPHP
 * @license    https://gitee.com/cq8044023/sdphp
 */
class Server
{
    private $serv;
    public function __construct() {
        $this->serv = new swoole_server("0.0.0.0", 6003);
        $this->serv->set(array(
            'worker_num' => 8,
            'daemonize' => false,
            'max_request' => 10000,
            'dispatch_mode' => 2,
            'package_max_length' => 8192,
            'open_length_check'=> true,
            'package_length_offset' => 0,
            'package_body_offset' => 4,
            'package_length_type' => 'N'
        ));
        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Close', array($this, 'onClose'));
        $this->serv->start();
    }
    public function onStart( $serv ) {
        echo "Start\n";
    }
    public function onConnect( $serv, $fd, $from_id ) {
        echo "Client {$fd} connect\n";
        
    }
    public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
        $length = unpack("N" , $data)[1];
        echo "Length = {$length}\n";
        $msg = substr($data,-$length);
        echo "Get Message From Client {$fd}:{$msg}\n";
    }
    public function onClose( $serv, $fd, $from_id ) {
        echo "Client {$fd} close connection\n";
    }
}
new Server();



$http_server = new swoole_http_server('0.0.0.0',9607);
$http_server->set(array('daemonize'=> false));
$http_server->on('request',function ($request, $response) {
    $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
//......设置各个回调......
//多监听一个tcp端口，对外开启tcp服务，并设置tcp服务器的回调
$tcp_server = $http_server->addListener('0.0.0.0', 9608, SWOOLE_SOCK_TCP);
//默认新监听的端口 9999 会继承主服务器的设置，也是 Http 协议
//需要调用 set 方法覆盖主服务器的设置
$tcp_server->set(array());
$tcp_server->on("receive", function ($serv, $fd, $threadId, $data) {
    /* $info = $serv->connection_info($fd);
    //来自9502的内网管理端口
    if($info['from_port'] == 9502) {
        $serv->send($fd, "welcome admin\n");
    }
    echo $data; */
});
$http_server->start();
        